package com.doordu.soa.service.data.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.doordu.soa.service.comm.ResultCode;
import com.doordu.soa.service.comm.ResultData;
import com.doordu.soa.service.data.service.ParkingEntryRecordService;
import com.doordu.soa.service.data.vo.RequestVo;
import com.doordu.soa.service.web.annotation.NotLogin;
import com.doordu.soa.service.web.annotation.Ver;
import com.doordu.soa.service.web.utils.BaseController;

import file.GZIPUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import sun.misc.BASE64Decoder;
@Api(tags = "ParkingEntryRecord", description = "车辆进出记录信息接口")
@RestController
@RequestMapping("/parking/entryEexitRecord")
public class ParkingEntryRecordController extends BaseController {

	@Value("${oss.accessKeyId}")
	private String ossAccessKeyId;

	@Value("${oss.accessSecret}")
	private String ossAccessSecret;

	@Value("${oss.endpoint}")
	private String endpoint;
	@Value("${oss.bucketName}")
	private String bucketName;

	@Value("${file.parentPath}")
	private String parentPath;

	private final Logger logger = LoggerFactory.getLogger(ParkingEntryRecordController.class);

	@Autowired
	private ParkingEntryRecordService parkingEntryRecordService;

	@ApiOperation(value = "上报停车场出入数据", notes = "上报停车场出入数据")
	@ApiResponses({ @ApiResponse(code = 200, message = "处理成功") })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path", required = true, dataType = "String", defaultValue = "v1"),
			@ApiImplicitParam(name = "data", value = "请求数据体", paramType = "query", required = true, dataType = "String"), })
	@RequestMapping(path = "/{ver}", method = RequestMethod.POST)
	@Ver("1")
	public ResponseEntity<Object> createParkingEntryRecord(RequestVo requestVo, HttpServletRequest request) {
		if (requestVo.getGzipFlag().intValue() == 1) {
			try {
				requestVo.setData(GZIPUtils.uncompressToString(GZIPUtils.compress(requestVo.getData())));
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		if (StringUtils.isBlank(requestVo.getData())) {
			return checkParamError("请求体data数据,gzip压缩有误");
		}
		requestVo.setCompanyId(getCompanyId(request));
		ResultData<Object> resultData = new ResultData<Object>(ResultCode.RESPONSE_SUCCESS);
		try {
			parkingEntryRecordService.insertData(resultData, requestVo, "/parking/lot/v1", "上报停车场数据");
			if (null != resultData && resultData.getCode().equals(ResultCode.RESPONSE_SUCCESS)) {
				return okResponse(resultData.getData(), resultData.getMsg(), resultData.getDesc());
			}
			return resultDataError(resultData);
		} catch (Exception e) {
			logger.error("", e);
			return error(ResultCode.RESPONSE_INTRANET_ERROR, e.getMessage());
		}
	}

	// @ApiOperation(value = "上报参数data参数校验-示例", notes = "上报参数data参数校验-示例")
	// @ApiResponses({ @ApiResponse(code = 200, message = "处理成功") })
	// @ApiImplicitParams({
	// @ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path",
	// required = true, dataType = "String", defaultValue = "v1") })
	// @RequestMapping(path = "/demo/{ver}", method = RequestMethod.POST)
	// @Ver("1")
	// @NotLogin
	// public ResponseEntity<Object>
	// createParkingEntryRecordDemo(ParkingEntryRecordVo parkingEntryRecordVo) {
	// String errorMsg = checkData(parkingEntryRecordVo);
	// if (StringUtils.isNotBlank(errorMsg)) {
	// return checkParamError(errorMsg);
	// }
	// return ok("操作成功");
	// }

	//

	//
	// @ApiOperation(value = "上传文件到阿里云", notes = "-")
	// @ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
	// @ApiImplicitParams({
	// @ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path",
	// required = true, dataType = "String", defaultValue = "v1"),
	// @ApiImplicitParam(name = "data", value = "图片base64", paramType = "query",
	// required = true, dataType = "String", allowableValues = ""), })
	// @RequestMapping(value = "/uploadFile/{ver}", method = RequestMethod.POST)
	// @Ver("1")
	// @NotLogin
	// public ResponseEntity<Object> uploadFile(HttpServletRequest request,
	// RequestVo requestVo) {
	// Map<String, Object> result = new HashMap<>();
	// try {
	// String errorMsg = checkData(requestVo);
	// if (StringUtils.isNotBlank(errorMsg)) {
	// return checkParamError(errorMsg);
	// }
	// if(requestVo.getGzipFlag().intValue()==1){
	// try{
	// requestVo.setData(GZIPUtils.uncompressToString(GZIPUtils.compress(requestVo.getData())));
	// }catch(Exception e){
	// logger.error("",e);
	// }
	// }
	// /** 单次-JSON解析判断 */
	// ImageVo imageVo=null;
	// try {
	// imageVo= JSONObject.parseObject(requestVo.getData(), ImageVo.class);
	// } catch (Exception e) {
	// logger.error("", e);
	// throw new JSONDefineException("上报数据的data的JSON格式错误");
	// }
	// if(StringUtils.isBlank(requestVo.getData())){
	// return checkParamError("请求体data数据,gzip压缩有误");
	// }
	// if (StringUtils.isBlank(imageVo.getImgFile())) {
	// return checkParamError("文件为空");
	// }
	// if (null == imageVo.getType()) {
	// return checkParamError("type不能为空");
	// }
	// if (StringUtils.isBlank(imageVo.getDataId())) {
	// return checkParamError("dataId不能空");
	// }
	// Integer companyId = getCompanyId(request);
	// String fileKey = uploadAliyun(imageVo.getImgFile(), endpoint, companyId);
	// logger.error("fileKey:" + fileKey);
	// boolean flag = parkingEntryRecordService.setImage(companyId,
	// imageVo.getDataId(), Integer.valueOf(imageVo.getType()), fileKey);
	// if (flag) {
	// return ok("操作成功");
	// }
	// return ok("操作成功");
	// } catch (Exception e) {
	// result.put("code", "400");
	// result.put("message", "上传文件出现异常");
	// logger.error("上传文件出现异常:{}", e);
	// }
	//
	// return error("400", "上传文件出现异常");
	// }

//	@ApiOperation(value = "上传文件到阿里云", notes = "-")
//	@ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path", required = true, dataType = "String", defaultValue = "v1"),
//			 })
//	@RequestMapping(value = "/uploadFile2/{ver}", method = RequestMethod.POST)
//	@Ver("1")
//	@NotLogin
//	public ResponseEntity<Object> uploadFile2(HttpServletRequest request, ImageVo imgVo) {
//		
//		Map<String, Object> result = new HashMap<>();
//		try {
//			logger.error(imgVo.toString());
//			/*if (null == imgFile) {
//				return checkParamError("图片为空");
//			}
//			if (null == type) {
//				return checkParamError("type不能为空");
//			}
//			if (StringUtils.isBlank(dataId)) {
//				return checkParamError("dataId不能空");
//			}*/
//			Integer companyId = getCompanyId(request);
//			String fileKey = uploadAliyun(imgVo.getImgFile(), endpoint, companyId);
//			boolean flag = parkingEntryRecordService.setImage(companyId, imgVo.getDataId(),imgVo.getType(), fileKey);
//			Map<String,String> data=new HashMap<>();
//			if (flag) {
//				data.put("flag", "1");
//			}else{
//				data.put("flag", "0");
//			}
//			data.put("fileKey", "http://doordustorage.oss-cn-shenzhen.aliyuncs.com/"+fileKey);
//			return ok(data);
//		} catch (Exception e) {
//			result.put("code", "400");
//			result.put("message", "上传文件出现异常");
//			logger.error("上传文件出现异常:{}", e);
//		}
//
//		return error("400", "上传文件出现异常");
//	}
	
	
	@ApiOperation(value = "上传文件到阿里云", notes = "-")
	@ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
	@ApiImplicitParams({
			@ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path", required = true, dataType = "String", defaultValue = "v1"),
			@ApiImplicitParam(name = "accessToken", value = "token信息", paramType = "query", required = true, dataType = "String", allowableValues = ""),
			@ApiImplicitParam(name = "method", value = "服务方法", paramType = "query", required = true, dataType = "String", defaultValue = "/parking/entryEexitRecord/v1"),
			@ApiImplicitParam(name = "type", value = "图片类型:1入场 2:出场", paramType = "query", required = true, dataType = "String", defaultValue = "1"),
			@ApiImplicitParam(name = "dataId", value = "数据id", paramType = "query", required = true, dataType = "String", allowableValues = ""),
			@ApiImplicitParam(name = "imgFile", value = "图片base64", paramType = "query", required = true, dataType = "String", allowableValues = ""), })
	@RequestMapping(value = "/uploadFile/{ver}", method = RequestMethod.POST)
	@Ver("1")
	@NotLogin
	public ResponseEntity<Object> uploadFile(HttpServletRequest request, Integer type, String imgFile, String dataId,
			String accessToken, String method) {
		logger.error("****type:" + type + "  dataId" + dataId + " accessToken:" + accessToken + " method:" + method);
		Map<String, Object> result = new HashMap<>();
		try {
			if (null == imgFile) {
				return checkParamError("图片为空");
			}
			if (null == type) {
				return checkParamError("type不能为空");
			}
			if (StringUtils.isBlank(dataId)) {
				return checkParamError("dataId不能空");
			}
			Integer companyId = getCompanyId(request);
			String fileKey = uploadAliyun(imgFile, endpoint, companyId);
			boolean flag = parkingEntryRecordService.setImage(companyId, dataId, type, fileKey);
			Map<String,String> data=new HashMap<>();
			if (flag) {
				data.put("flag", "1");
			}else{
				data.put("flag", "0");
			}
			data.put("fileKey", "http://doordustorage.oss-cn-shenzhen.aliyuncs.com/"+fileKey);
			return ok(data);
		} catch (Exception e) {
			result.put("code", "400");
			result.put("message", "上传文件出现异常");
			logger.error("上传文件出现异常:{}", e);
		}

		return error("400", "上传文件出现异常");
	}

//	@ApiOperation(value = "上传文件到阿里云", notes = "-")
//	@ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path", required = true, dataType = "String", defaultValue = "v1"),
//			@ApiImplicitParam(name = "accessToken", value = "token信息", paramType = "query", required = true, dataType = "String", allowableValues = ""),
//			@ApiImplicitParam(name = "method", value = "服务方法", paramType = "query", required = true, dataType = "String", defaultValue = "/parking/entryEexitRecord/v1"),
//			@ApiImplicitParam(name = "type", value = "图片类型:1入场 2:出场", paramType = "query", required = true, dataType = "String", defaultValue = "1"),
//			@ApiImplicitParam(name = "dataId", value = "数据id", paramType = "query", required = true, dataType = "String", allowableValues = ""),
//			@ApiImplicitParam(name = "imgFile", value = "图片byte[]", paramType = "query", required = true, dataType = "String", allowableValues = ""), })
//	@RequestMapping(value = "/uploadFile1/{ver}", method = RequestMethod.POST)
//	@Ver("1")
//	@NotLogin
//	public ResponseEntity<Object> uploadFile1(HttpServletRequest request, Integer type, byte[] imgFile, String dataId,
//			String accessToken, String method) {
//		logger.error("****type:" + type + "  dataId" + dataId + " accessToken:" + accessToken + " method:" + method);
//		Map<String, Object> result = new HashMap<>();
//		try {
//			request.getInputStream();
//			if (null == imgFile) {
//				return checkParamError("图片为空");
//			}
//			if (null == type) {
//				return checkParamError("type不能为空");
//			}
//			if (StringUtils.isBlank(dataId)) {
//				return checkParamError("dataId不能空");
//			}
//			Integer companyId = getCompanyId(request);
//			String fileKey = uploadAliyun1(imgFile, endpoint, companyId);
//			logger.error("fileKey:" + fileKey);
//			boolean flag = parkingEntryRecordService.setImage(companyId, dataId, type, fileKey);
//			if (flag) {
//				return ok("操作成功");
//			}
//			return ok("操作成功");
//		} catch (Exception e) {
//			result.put("code", "400");
//			result.put("message", "上传文件出现异常");
//			logger.error("上传文件出现异常:{}", e);
//		}
//
//		return error("400", "上传文件出现异常");
//	}
//
//	@ApiOperation(value = "后端上传文件到阿里云", notes = "-")
//	@ApiResponses({ @ApiResponse(code = 200, message = "操作成功") })
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "ver", value = "接口版本", paramType = "path", required = true, dataType = "String", defaultValue = "v1"),
//			@ApiImplicitParam(name = "accessToken", value = "token信息", paramType = "query", required = true, dataType = "String", allowableValues = ""),
//			@ApiImplicitParam(name = "method", value = "服务方法", paramType = "query", required = true, dataType = "String", defaultValue = "/parking/entryEexitRecord/v1"),
//			@ApiImplicitParam(name = "type", value = "图片类型:1入场 2:出场", paramType = "query", required = true, dataType = "String", defaultValue = "1"),
//			@ApiImplicitParam(name = "dataId", value = "数据id", paramType = "query", required = true, dataType = "String", allowableValues = "") })
//	@RequestMapping(value = "/uploadFile2/{ver}", method = RequestMethod.POST)
//	@Ver("1")
//	@NotLogin
//	public ResponseEntity<Object> uploadFile2(HttpServletRequest request, Integer type, String dataId, String accessToken,
//			String method, @RequestParam(name = "imgFile", required = true) MultipartFile multipartFile) {
//		Map<String, Object> result = new HashMap<>();
//		try {
//			if (multipartFile.isEmpty()) {
//				result.put("code", "400");
//				result.put("message", "文件为空");
//				return checkParamError("文件为空");
//			}	
//			Integer companyId = getCompanyId(request);
//
//			String fileDir = "doordu_admin/parking/"+companyId;
//			
//
//			String bucketName = "doordustorage";
//			String protorl = "http";
//			String endpoint = protorl + "://oss-cn-shenzhen.aliyuncs.com";
//			OSSClient client = new OSSClient(endpoint, ossAccessKeyId, ossAccessSecret);
//			ObjectMetadata metadata = new ObjectMetadata();
//			metadata.setContentType(multipartFile.getContentType());
//			metadata.setContentLength(multipartFile.getSize());
//
//			String fileName = UUID.randomUUID().toString().replace("-", "");
//			fileName = fileName.substring(1, 20) + System.currentTimeMillis();
//			String fileSuffix = multipartFile.getOriginalFilename()
//					.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
//			String fileKey = fileDir + "/" + fileName + fileSuffix;
//			logger.warn("上传到阿里云的fileKey:{}", fileKey);
//			client.putObject(bucketName, fileKey, multipartFile.getInputStream(), metadata);
//			logger.warn("上传文件结束");
//
//			result.put("code", "200");
//			result.put("message", "上传文件成功");
//			result.put("data", fileKey);
//			logger.error("path:"+fileKey);
//			boolean flag = parkingEntryRecordService.setImage(companyId, dataId, type, fileKey);
//			if (flag) {
//				return ok("操作成功:"+fileKey);
//			}
//			// 关闭client
//			client.shutdown();
//		} catch (IOException e) {
//			result.put("code", "400");
//			result.put("message", "上传文件出现异常");
//			logger.error("上传文件出现异常:{}", e);
//		}
//
//		return ok("上传文件成功");
//	}

	private String uploadAliyun(String imgFile, String endpoint, Integer companyId) {
		String fileDir = "doordu_admin/parking/" + companyId;
		OSSClient client = new OSSClient(endpoint, ossAccessKeyId, ossAccessSecret);
		//byte[] imageB = Base64.decodeBase64(imgFile);
		// Base64解码
		BASE64Decoder c=new BASE64Decoder();
		Date now = new Date();
		String fileName =  String.valueOf(now.getTime());
		try {
			//FileOperatorUtils.newFile(parentPath+"/txt/"+fileName+".txt", imgFile.getBytes());
			imgFile=imgFile.replaceAll(" ", "+"); 
			byte[] imageB = c.decodeBuffer(imgFile);
			//FileOperatorUtils.newFile(parentPath+"/txt/replace/"+fileName+".txt", imgFile.getBytes());
			//byte[] imageB =decoder.encodeBuffer(imgFile);
			InputStream in = new ByteArrayInputStream(imageB);
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentType("jpg");
			try {
				String fileSuffix = ".jpg";
				String fileKey = fileDir + "/" + fileName + fileSuffix;
				logger.warn("上传到阿里云的fileKey:{}", fileKey);
				client.putObject(bucketName, fileKey, in, metadata);
				logger.warn("上传文件结束");
				// 关闭client
				client.shutdown();
				return fileKey;
			} catch (Exception e) {
				logger.error("", e);
				fileName = UUID.randomUUID().toString().replace("-", "");
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	
		return null;

	}
}
